<script lang="ts" setup name="ReceiveSheetEdit">
import { CircleClose, Delete } from '@element-plus/icons-vue'
import { FormInstance, TableInstance } from 'element-plus'
import { DefaultRow, TableColumnCtx } from 'element-plus/es/components/table/src/table/defaults.mjs'
import { getSupplierAPI, getWaresCategoryListAPI } from '~/src/api/goods'
import { Inventory } from '~/src/api/interface/goods'
import { Procure } from '~/src/api/interface/procure'
import { StoreManagement } from '~/src/api/interface/storeManagement'
import {
  checkStockOutAPI,
  createStockOutAPI,
  editStockOutAPI,
  getBreakageResultAPI,
  getStockOutAPI,
  getStockPlanGoodsListAPI,
  getStoreHouseAPI,
} from '~/src/api/procure'
import { getDepartmentAPI, getStaffInfoAPI } from '~/src/api/storeManagement'
import { replaceArrayItems } from '~/src/utils'
import { formatDate } from '~/src/utils/date-formatter'
import QuickDialog from '../components/QuickDialog.vue'
import SelectTreeTable from '/@vab/components/SelectTreeData/index.vue'

const route = useRoute()
const router = useRouter()
const documentStatus = ref('add')
const ruleFormRef = ref<FormInstance>()
const purchaseForm = ref<Procure.BreakageSheetOrderInfo>({
  id: 0,
  type: 1,
  // orderType: 1,
  orderNo: '',
  supplierId: 0,
  outDate: formatDate(0, 'start', 'yyyy-MM-dd'),
  trackingNo: '',
  status: 1,
  checkFlag: false,
  remark: '',
  // sourceId: '',
  printStatus: 0,
  stockoutdetailList: [],
  // 后面添加
  houseId: 0,
  departmentId: 0,
  staffId: 0,
  // customerId: null,
  houseStaffId: null,
})
interface SummaryMethodProps<T = Inventory.ResPurchaseList> {
  columns: TableColumnCtx<T>[]
  data: T[]
}
onMounted(async () => {
  documentStatus.value = route.query.type as string
  await Promise.all([getSupplierList(), getStore(), getDepartmentList(), getStaffsList(), getCustomsList()])
  if (route.query.id) {
    const res = await getStockOutAPI({ id: route.query.id })
    Object.assign(purchaseForm.value, res.data) // 直接将res.data 复制给 purchaseForm
    // Object.keys(purchaseForm).forEach((key) => {
    // const k = key as keyof typeof purchaseForm 类型断言
    //   if (res.data.hasOwnProperty(k)) {
    //     purchaseForm[k] = res.data[k]
    //   }
    // })
  } else {
    purchaseForm.value.supplierId = supplierList.value[0].id
  }
  if (route.query.type !== 'audited') {
    add()
  }
})

// 供应商
const supplierList = ref<Inventory.SupplierList[]>([])
const getSupplierList = async () => {
  const res = await getSupplierAPI({ pageNum: 1, pageSize: 9999 })
  supplierList.value = res.data.list
}

// 获取仓库列表
const storeList = ref<Procure.StoreHouse[]>([])
// const defaultHouserId = ref("");
const getStore = async () => {
  const res = await getStoreHouseAPI({ pageNum: 1, pageSize: 9999 })
  storeList.value = res.data.list
  storeList.value.forEach((v) => {
    if (v.isDefault) {
      purchaseForm.value.houseId = v.id
    }
  })
}

// 部门列表
const departmentList = ref<StoreManagement.DepartmentList[]>([])
const getDepartmentList = async () => {
  const res = await getDepartmentAPI({ pageNum: 1, pageSize: 9999 })
  departmentList.value = res.data.list
  purchaseForm.value.departmentId = res.data.list.length > 0 ? res.data.list[0].id : 0
}
// 员工列表
const staffList = ref<StoreManagement.StaffInfo[]>([])
const getStaffsList = async () => {
  const res = await getStaffInfoAPI({ pageNum: 1, pageSize: 9999 })
  staffList.value = res.data.list
  purchaseForm.value.staffId = res.data.list.length > 0 ? res.data.list[0].id : 0
}
// 领用原因
const customList = ref<Procure.BreakageResult[]>([])
const getCustomsList = async () => {
  const res = await getBreakageResultAPI({ pageNum: 1, pageSize: 9999, commTypeId: 1 })
  customList.value = res.data.list
  purchaseForm.value.customerId = res.data.list.length > 0 ? res.data.list[0].id : 0
}

const rules = reactive({
  stockoutdetailList: [{ required: true, message: '请添加商品' }],
  departmentId: [{ required: true, message: '请选择部门' }],
  staffId: [{ required: true, message: '请选择领用人' }],
  // houseStaffId: [{ required: true, message: "请选择库管人" }]
  customerId: [{ required: true, message: '请选择领用类型' }],
})
interface SummaryMethodProps<T extends DefaultRow = Inventory.ResPurchaseList> {
  columns: TableColumnCtx<T>[]
  data: T[]
}
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const props: string[] = ['quantity', 'amount', 'giftQuantity']
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (!props.includes(column.property)) {
      sums[index] = ''
      return
    }

    let valuesToSum: number[] = []
    data.forEach((item: any) => {
      if (column.property === 'quantity' && item.isGift) {
        return // 如果isGift为true，则不统计quantity
      }
      if (column.property === 'amount' && item.isGift) {
        return // 如果isGift为true，则不统计amount
      }
      if (column.property === 'giftQuantity' && !item.isGift) {
        return // 如果isGift为false，则不统计giftQuantity
      }
      const value = Number(item[column.property])
      if (!Number.isNaN(value)) {
        valuesToSum.push(value)
      }
    })

    if (valuesToSum.length > 0) {
      sums[index] = `${valuesToSum.reduce((prev, curr) => prev + curr, 0)}`
    } else {
      sums[index] = ''
    }
  })
  return sums
}

// 新增供应商end

const add = (index: number = purchaseForm.value.stockoutdetailList.length) => {
  purchaseForm.value.stockoutdetailList.splice(index, 0, {
    goodsName: '',
    goodsId: 0,
    // products: "",
    productsId: 0,
    productName: '',
    quantity: 0,
    price: 0,
    amount: 0,
    taxRate: 0,
    isGift: false,
    giftQuantity: 0,
    remark: '',
    // customerId: customList.value[0].id
    customerId: customList.value.length > 0 ? customList.value[0].id : 0,
  })
}
const remove = (row: Inventory.ResGoodsList, index: number) => {
  if (!row.productsId) return
  purchaseForm.value.stockoutdetailList.splice(index, 1)
}

const delSpecRow = (index: number) => {
  purchaseForm.value.stockoutdetailList.splice(index, 1)
}

const onSearchCode = (value: string | number) => {
  if (Object.entries(value).length !== 0) {
    openSelectTreeTable('选择商品', value)
  }
}

const handleSelectedTreeList = (val: any) => {
  if (val.list.length > 0) {
    let list = val.list.map((im: any) => {
      return {
        goodsName: im.name,
        goodsId: im.id,
        products: im.productName,
        productsId: im.productsId,
        productName: im.productName,
        quantity: 1,
        barcode: im.barcode,
        price: im.purPrice,
        costPrice: im.costPrice,
        amount: im.purPrice,
        taxRate: 0,
        isGift: false,
        giftQuantity: 0,
        planQuantity: im.planQuantity,
        unitName: im.unitName,
        remark: '',
        customerId: customList.value.length > 0 ? customList.value[0].id : null,
      }
    })
    purchaseForm.value.stockoutdetailList = replaceArrayItems(list, purchaseForm.value.stockoutdetailList, 'goodsId')
    // purchaseForm.value.stockoutdetailList = list;
    if (purchaseForm.value.stockoutdetailList.some((item) => !item.goodsId)) return
    add()
  }
}

const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null)
const openSelectTreeTable = (title: string, searchVal?: string | number) => {
  const params = {
    title,
    isView: false,
    searchVal,
    index: 0,
    mate: 'productsId',
    selTags: purchaseForm.value.stockoutdetailList.map((i: any) => {
      i.name = i.goodsName
      i.id = i.productsId
      return i
    }),
    columns: [
      { type: 'selection', width: 80 },
      { prop: 'barcode', label: '编码', align: 'left', width: 200 },
      { prop: 'name', label: '商品名称', align: 'left', minWidth: 220 },
      { prop: 'productName', label: '规格', align: 'left', minWidth: 100 },
      { prop: 'unitName', label: '单位', align: 'left', minWidth: 160 },
      // { prop: "posPrice", label: "商品价格", minWidth: 120 }
      { prop: 'purPrice', label: '采购价格', minWidth: 120 },
    ],
    idName: 'goodsCategoryId',
    treeApi: getWaresCategoryListAPI,
    api: getStockPlanGoodsListAPI,
    apiParams: { houseId: purchaseForm.value.houseId },
  }
  selectTreeTableRef.value?.acceptParams(params)
}

const onChangeAmo = (index: number) => {
  purchaseForm.value.stockoutdetailList[index].amount = (
    (purchaseForm.value.stockoutdetailList[index].price as number) * (purchaseForm.value.stockoutdetailList[index].quantity as number)
  ).toFixed(2)
}

// 开启极速输入模式
const isQuick = ref(false)
const isQuickData = ref<number[]>([0, 1, 2])
const quickDialogRef = ref<InstanceType<typeof QuickDialog>>()
const inputList = [
  { label: '商品条码', value: 0 },
  { label: '数量', value: 1 },
  { label: '金额', value: 2 },
  // { label: '税率', value: 3 },
]
const quickSwitch = () => {
  if (isQuick.value) {
    isQuick.value = false
    isQuickData.value = [0, 1, 2]
    return
  }
  openQuickDialog()
}
const openQuickDialog = () => {
  quickDialogRef.value?.putParams({
    title: '',
    list: inputList,
    data: {
      list: isQuickData.value,
    },
  })
}
// 开启极速模式
const onQuick = (e: number[]) => {
  if (e.length >= inputList.length) return (isQuick.value = false)
  isQuick.value = true
  isQuickData.value = e
}
// 保存所有输入框 ref 的二维数组
const inputRefs = ref<(any | null)[][]>([])
const setInputRef = (rowIndex1: number, colIndex: number, el: any) => {
  if (!inputRefs.value[rowIndex1]) {
    inputRefs.value[rowIndex1] = []
  }
  inputRefs.value[rowIndex1][colIndex] = el
}
const handleEnter = (rowIndex1: number, colIndex: number) => {
  const value = inputRefs.value[rowIndex1][colIndex]
  if (!value) return // 没填，不跳
  // 是否开启极速输入模式
  if (!isQuick.value) {
    if (!colIndex) {
      // 1.barcode
      // 可搜索数据然后在跳转,barcode
      searchBarcode(rowIndex1, colIndex + 1)
      return
    }
    const isLastCol = inputList[inputList.length - 1].value === colIndex
    if (isLastCol) {
      // 3.换行
      const nextRow = rowIndex1 + 1
      if (inputRefs.value[nextRow] && inputRefs.value[nextRow][0]) {
        nextTick(() => {
          inputRefs.value[nextRow][0].focus()
          changeAmunt(rowIndex1)
        })
      }
    } else {
      // 2.正常数量行
      const nextCol = colIndex + 1
      if (inputRefs.value[rowIndex1][nextCol]) {
        nextTick(() => {
          inputRefs.value[rowIndex1][nextCol].focus()
          changeAmunt(rowIndex1)
        })
      }
    }
  } else {
    // 极速输入模式
    if (isQuickData.value.includes(inputList[0].value) && !colIndex) {
      // 要做处理😢极速模式选择商品后那个有焦点
      searchBarcode(rowIndex1, colIndex + 1)
      return
    }
    if (colIndex) {
      if (colIndex === inputList[1].value || colIndex === inputList[2].value) {
        // 要修改价格
        changeAmunt(rowIndex1)
      }

      if (colIndex === isQuickData.value[isQuickData.value.length - 1]) {
        // 表示已经是最后一项，换行
        const nextRow = rowIndex1 + 1
        nextTick(() => {
          inputRefs.value[nextRow][isQuickData.value[0]].focus()
        })
        return
      }
      nextTick(() => {
        inputRefs.value[rowIndex1][isQuickData.value[isQuickData.value.findIndex((item) => colIndex === item) + 1]].focus()
      })
    }
  }
}
const searchBarcode = async (row: number, col: number) => {
  goodsList.value = []
  if (purchaseForm.value.stockoutdetailList[row].goodsName && purchaseForm.value.stockoutdetailList[row].barcode === barcodeValue.value) {
    // 不开启极速搜索
    if (!isQuick.value) {
      // 当前行有数据,直接不搜索
      inputRefs.value[row][1]?.focus()
      return
    } else {
      // 当前行有数据,直接不搜索
      if (isQuickData.value.length <= 1) {
        inputRefs.value[row + 1][0]?.focus()
      } else {
        inputRefs.value[row][isQuickData.value.find((item) => item) as number]?.focus()
      }
      return
    }
  }
  if (!purchaseForm.value.stockoutdetailList[row].barcode || purchaseForm.value.stockoutdetailList[row].barcode!.length < 2) {
    ElMessage.info('请输入两个字以上关键字')
    return
  }
  const res = await getStockPlanGoodsListAPI({
    pageNum: 1,
    pageSize: 20,
    isDefault: 0,
    isRetail: 1,
    houseId: purchaseForm.value.houseId,
    name: purchaseForm.value.stockoutdetailList[row].barcode,
  })
  if (res.data.list.length === 1) {
    rowIndex.value = row
    popoverClick(res.data.list[0])
    isOne.value = true
  } else {
    goodsList.value = res.data.list
    popoverVis.value = true
    rowIndex.value = row
    goodsRowsCurrent.value = 0
    setCurrent()
  }
}
// 商品实现键盘上下移动选中效果start
const goodsTableRef = ref<TableInstance>()
const goodsRowsCurrent = ref(0) // 拿到数据选中当前第一行,当他的索引是多少是goodslist就拿哪一个
const setCurrent = () => {
  goodsTableRef.value?.setCurrentRow(goodsList.value[goodsRowsCurrent.value])
  if (popoverVis.value && goodsList.value.length > 0) {
    nextTick(() => {
      inputRefs.value[rowIndex.value][0].blur()
      keyboardWrapperRef.value?.focus()
    })
  }
}
// 键盘控制上下选择
const handleKeydown = (e: KeyboardEvent, index: number) => {
  const list = goodsList.value
  if (!list.length) return
  if (e.key === 'ArrowDown') {
    e.preventDefault()
    goodsRowsCurrent.value = (goodsRowsCurrent.value + 1) % list.length // 最后一行回到第一行
    goodsTableRef.value!.setCurrentRow(list[goodsRowsCurrent.value])
    nextTick(() => {
      goodsTableRef.value!.setScrollTop(getRowRelativeTop(goodsRowsCurrent.value).top)
    })
  }
  if (e.key === 'ArrowUp') {
    e.preventDefault()
    goodsRowsCurrent.value = (goodsRowsCurrent.value - 1 + list.length) % list.length // 第一行回到最后一行
    goodsTableRef.value!.setCurrentRow(list[goodsRowsCurrent.value])
    nextTick(() => {
      goodsTableRef.value!.setScrollTop(getRowRelativeTop(goodsRowsCurrent.value).top)
    })
  }
  if (e.key === 'Enter') {
    e.preventDefault()
    const current = list[goodsRowsCurrent.value]
    if (current) popoverClick(current)
  }
}
// 获取指定索引行相对于表格容器的 top 坐标
const getRowRelativeTop = (rowIndex: number): { top: number } => {
  if (!goodsTableRef.value) return { top: 0 }
  // 获取表格容器（整个 el-table 的 DOM 元素)
  const tableEl = goodsTableRef.value.$el as HTMLElement
  if (!tableEl) return { top: 0 }
  // 获取表格 body 容器（行所在的滚动容器）
  const bodyWrapper = goodsTableRef.value.$refs.bodyWrapper as {
    querySelectorAll(ele: string): HTMLElement[]
  }
  if (!bodyWrapper) return { top: 0 }
  // 获取指定行的 DOM 元素
  const rows = bodyWrapper.querySelectorAll('.el-table__row')
  if (!rows[rowIndex]) return { top: 0 } // 索引越界
  // 计算行相对于视口的 top 坐标
  const rowRect = rows[rowIndex].getBoundingClientRect()
  // 计算表格容器相对于视口的 top 坐标
  const tableRect = tableEl.getBoundingClientRect()

  // 行相对于表格容器的 top = 行视口 top - 表格视口 top
  const relativeTop = rowRect.top - tableRect.top
  // rows[rowIndex].scrollIntoView({ behavior: 'smooth' })
  return { top: relativeTop }
}

const keyboardWrapperRef = ref<HTMLDivElement | null>(null)
// 商品实现键盘上下移动选中效果end

// 搜索编码数据
const goodsList = ref<Procure.GetStockPlanGoodsList[]>([]) // 当前搜索数据
const rowIndex = ref(0) // 搜索行数据
const popoverVis = ref(false) // 搜索到数据后用于展示表格
const barcodeValue = ref<string | undefined>('')
const isOne = ref(false)
const onBarcodeFocus = (index: number) => {
  // barcode 用于当barcode有数据时候重新输入判断要不要搜索失去焦点时候把数据重新赋值
  rowIndex.value = index
  onFocus(index, 0)
  if (purchaseForm.value.stockoutdetailList[index].barcode) {
    nextTick(() => {
      barcodeValue.value = purchaseForm.value.stockoutdetailList[index].barcode
    })
  }
}
const onBarcodeBlur = (index: number) => {
  if (!popoverVis.value) {
    if (barcodeValue.value) {
      nextTick(() => {
        purchaseForm.value.stockoutdetailList[index].barcode = barcodeValue.value
        barcodeValue.value = ''
      })
      return
    }
    if (!isOne.value) {
      nextTick(() => {
        purchaseForm.value.stockoutdetailList[index].barcode = ''
        isOne.value = false
      })
    }
  }
}
const onClosePop = (index: number) => {
  popoverVis.value = false
  if (barcodeValue.value) {
    purchaseForm.value.stockoutdetailList[index].barcode = barcodeValue.value
    return
  }
  purchaseForm.value.stockoutdetailList[index].barcode = ''
}

const popoverClick = (e: Procure.GetStockPlanGoodsList) => {
  // 选中行
  const i = purchaseForm.value.stockoutdetailList.findIndex((item) => item.productsId === e.productsId)
  if (i !== -1) {
    popoverVis.value = false
    ElMessageBox.confirm('当前商品已经添加，是否跳到对应行', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      nextTick(() => {
        if (purchaseForm.value.stockoutdetailList[rowIndex.value].goodsId) {
          purchaseForm.value.stockoutdetailList.splice(rowIndex.value - 1, 1)
        }
        goodsList.value = []
        inputRefs.value[i][0].focus()
      })
    })
    return
  }
  purchaseForm.value.stockoutdetailList[rowIndex.value] = {
    goodsName: e.name,
    goodsId: e.id,
    productsId: e.productsId,
    productName: e.productName,
    quantity: 1,
    barcode: e.barcode,
    price: e.purPrice,
    costPrice: e.costPrice,
    amount: e.purPrice,
    taxRate: 0,
    isGift: false,
    giftQuantity: 0,
    planQuantity: e.planQuantity,
    unitName: e.unitName,
    remark: '',
    customerId: customList.value.length > 0 ? customList.value[0].id : 0,
  }
  nextTick(() => {
    setTimeout(() => {
      if (!isQuick.value) {
        // 不开启极速模式
        inputRefs.value[rowIndex.value][1]?.focus()
      } else {
        // 开启极速模式
        if (isQuickData.value.length === 1) {
          inputRefs.value[rowIndex.value + 1][0]?.focus()
        } else {
          inputRefs.value[rowIndex.value][isQuickData.value[1]]?.focus()
        }
      }
      rowIndex.value = 0
    }, 50)
    // inputRefs.value[rowIndex.value][1].focus()
    // 重置数据
    goodsList.value = []
    popoverVis.value = false
    // rowIndex.value = 0
    if (!purchaseForm.value.stockoutdetailList.some((item) => !item.goodsName)) add()
  })
}

// 数据和采购价修改自动修改金额
const changeAmunt = (index: number) => {
  nextTick(() => {
    purchaseForm.value.stockoutdetailList[index].amount = Number(
      (
        (purchaseForm.value.stockoutdetailList[index].quantity as number) * (purchaseForm.value.stockoutdetailList[index].price as number)
      ).toFixed(4)
    )
  })
}
const onFocus = (row: number, col: number) => {
  nextTick(() => {
    inputRefs.value[row][col].select()
  })
}

const { useChangeDetailData } = useHandleDetail()
const onSubmit = async () => {
  if (purchaseForm.value.stockoutdetailList.filter((item) => item.goodsId).length < 1) return ElMessage.error('请添加商品')
  if (customList.value.length < 1) return ElMessage.error('请先添加领用类型')
  await ruleFormRef.value!.validate()
  try {
    purchaseForm.value.stockoutdetailList = purchaseForm.value.stockoutdetailList.filter((item) => item.goodsId && item.productsId)
    if (documentStatus.value === 'edit') {
      await useChangeDetailData(editStockOutAPI, purchaseForm.value, '/procure/receiveSheet')
    } else {
      await useChangeDetailData(createStockOutAPI, purchaseForm.value, '/procure/receiveSheet')
    }
  } catch (error) {
    add(purchaseForm.value.stockoutdetailList.length)
  }
}
// 确认收货并审核
const onSubmitGoods = async () => {
  if (purchaseForm.value.stockoutdetailList.filter((item) => item.goodsId).length < 1) return ElMessage.error('请添加商品')
  if (customList.value.length < 1) return ElMessage.error('请先添加领用类型')
  try {
    purchaseForm.value.stockoutdetailList = purchaseForm.value.stockoutdetailList.filter((item) => item.goodsId && item.productsId)
    await ruleFormRef.value!.validate()
    await useChangeDetailData(checkStockOutAPI, purchaseForm.value, '/procure/receiveSheet')
  } catch (error) {
    add(purchaseForm.value.stockoutdetailList.length)
  }
}
</script>

<template>
  <div class="auto-height-container flx-column">
    <header-line
      :confirmIsSHow="documentStatus !== 'audited'"
      :title="(route.query.id && +route.query.id ? (purchaseForm.checkFlag ? '查看' : '编辑') : '新增') + '领用单'"
      @on-submit="onSubmit()"
    >
      <template #button>
        <el-button v-if="!purchaseForm.checkFlag" style="margin: 5px" type="primary" @click="quickSwitch">
          {{ isQuick ? '关闭快速输入' : '开启极速输入模式' }}
        </el-button>
        <el-button v-if="documentStatus !== 'audited'" type="primary" @click="openSelectTreeTable('选择商品')">添加商品明细</el-button>
        <!-- v-if="stockPlanForm.status === 2"  -->
        <el-button v-if="!purchaseForm.checkFlag" type="primary" @click="onSubmitGoods">保存并审核</el-button>
      </template>
    </header-line>

    <el-form
      ref="ruleFormRef"
      :inline="true"
      label-position="right"
      label-suffix="："
      label-width="100px"
      :model="purchaseForm"
      :rules="rules"
    >
      <el-row :gutter="24">
        <el-col :span="5">
          <el-form-item label="领用单编号" prop="orderNo">
            <el-input v-model="purchaseForm.orderNo" class="width150" disabled placeholder="系统自动生成" />
          </el-form-item>
        </el-col>
        <!-- <el-form-item label="物流单号" prop="trackingNo">
        <el-input class="width150" v-model="purchaseForm.trackingNo" />
      </el-form-item> -->
        <el-col :span="5">
          <el-form-item label="领用日期" prop="outDate">
            <el-date-picker v-model="purchaseForm.outDate" class="width150" type="date" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
        <!-- lai后面添加 -->
        <el-col :span="5">
          <el-form-item v-if="storeList.length" label="领用仓库" prop="houseId">
            <el-select v-model="purchaseForm.houseId" class="width150" :disabled="documentStatus !== 'add'" placeholder="请选择">
              <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item v-if="departmentList.length" label="领用部门" prop="departmentId">
            <el-select v-model="purchaseForm.departmentId" class="width150" placeholder="请选择">
              <el-option v-for="item in departmentList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item v-if="staffList.length" label="领用人" prop="staffId">
            <el-select v-model="purchaseForm.staffId" class="width150" placeholder="请选择">
              <el-option v-for="item in staffList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="领用类型" prop="customerId">
            <el-select v-model="purchaseForm.customerId" class="width150" placeholder="请选择">
              <el-option v-for="item in customList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item v-if="staffList.length" label="库管员" prop="houseStaffId">
            <el-select v-model="purchaseForm.houseStaffId" class="width150" placeholder="请选择">
              <el-option v-for="item in staffList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="purchaseForm.remark" class="width150" placeholder="请填写" :rows="1" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="flex1">
      <el-table
        border
        :data="purchaseForm.stockoutdetailList"
        row-key="id"
        show-overflow-tooltip
        show-summary
        stripe
        style="width: 100%; height: 100%"
        :summary-method="getSummaries"
        tabindex="0"
      >
        <el-table-column align="center" label="序号" prop="index" width="60">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column v-if="documentStatus !== 'audited'" align="center" label="操作" prop="operation" width="80">
          <template #default="{ $index, row }">
            <el-button link size="small" type="primary" @click="add($index + 1)">
              <el-icon :color="`var(--el-color-primary)`"><circle-close /></el-icon>
            </el-button>
            <el-button :icon="Delete" link size="small" @click="remove(row, $index)" />
          </template>
        </el-table-column>
        <el-table-column label="商品条码" prop="barcode" width="250">
          <template #default="{ row, $index }">
            <el-popover placement="bottom-start" :visible="rowIndex === $index && popoverVis" :width="600">
              <div ref="keyboardWrapperRef" class="table-keyboard-wrapper" tabindex="0" @keydown.prevent="handleKeydown($event, $index)">
                <el-table
                  ref="goodsTableRef"
                  :data="goodsList"
                  highlight-current-row
                  row-key="productsId"
                  style="height: 250px"
                  @row-dblclick="popoverClick"
                >
                  <el-table-column label="条码" prop="barcode" width="200" />
                  <el-table-column label="代码" prop="sn" width="200" />
                  <el-table-column label="名称" prop="name" width="100" />
                  <el-table-column label="规格" prop="productName" width="120" />
                  <el-table-column label="单位" prop="unitName" width="120" />
                  <el-table-column label="采购价" prop="purPrice" width="100" />
                </el-table>
              </div>
              <div class="flx-justify-between">
                <div class="fsize12 pt10 pl5">提示：双击选中商品</div>
                <el-icon class="mt10" :size="18" @click="onClosePop($index)"><circle-close /></el-icon>
              </div>
              <template #reference>
                <el-input
                  :ref="(el) => setInputRef($index, 0, el)"
                  v-model="row.barcode"
                  placeholder=""
                  style="border: none !important"
                  @blur="onBarcodeBlur($index)"
                  @focus="onBarcodeFocus($index)"
                  @keydown.enter.prevent="handleEnter($index, 0)"
                >
                  <!-- @keyup.enter="handleKeyup($event, $index, 1, row.isGift)" -->
                  <template #prefix></template>
                </el-input>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="goodsName" width="200" />
        <el-table-column label="规格" prop="productName" width="100" />
        <el-table-column label="数量" prop="quantity" width="150">
          <template #default="{ row, $index }">
            <input-number-float
              :ref="(el) => setInputRef($index, 1, el)"
              v-model:modelValue="row.quantity"
              autofocus
              class="width100"
              @blur="changeAmunt($index)"
              @focus="onFocus($index, 1)"
              @keydown.enter.prevent="handleEnter($index, 1)"
            />
            <!-- @keyup.enter="handleKeyup($event, $index, 2, row.isGift)" -->
          </template>
        </el-table-column>
        <el-table-column label="单价" prop="price" width="180">
          <template #default="{ row, $index }">
            <input-number-float
              :ref="(el) => setInputRef($index, 2, el)"
              v-model:modelValue="row.price"
              class="width100"
              @blur="changeAmunt($index)"
              @focus="onFocus($index, 2)"
              @keydown.enter.prevent="handleEnter($index, 2)"
            />
            <!-- @keyup.enter="handleKeyup($event, $index, 3, row.isGift)" -->
            <!-- <el-input-number v-model="row.price" :controls="false" :min="0.01" /> -->
          </template>
        </el-table-column>
        <el-table-column label="金额" prop="amount" width="180">
          <template #default="{ row, $index }">
            <input-number-float v-model:modelValue="row.amount" class="width100" disabled />
            <!-- @keyup.enter="handleKeyup($event, $index, 4, row.isGift)" -->
          </template>
        </el-table-column>
        <el-table-column label="当前库存" prop="planQuantity" width="100" />
        <el-table-column label="单位名称" prop="unitName" width="100" />
        <el-table-column label="备注" prop="remark">
          <template #default="{ row, $index }">
            <el-input v-model="row.remark" :disabled="documentStatus === 'audited'" placeholder="" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <select-tree-table ref="selectTreeTableRef" @selected-list="handleSelectedTreeList" />
    <quick-dialog ref="quickDialogRef" @on-confirm="onQuick" />
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-table thead .el-table__cell) {
  padding: 5px 0;
  background: #f2f3f5;
}
:deep(.el-table tfoot .el-table__cell) {
  padding: 5px 0;
  background: #f2f3f5;
}
:deep(.el-table .el-table__cell) {
  padding: 0;
}
:deep(.el-form-item) {
  margin-bottom: 8px;
}
</style>
